<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/11/8
 * Time: 14:06
 */

namespace app\api\service;


use app\api\model\Behavior as BehaviorModel;
use app\api\model\BehaviorType;
use app\api\model\CardBase;
use app\api\model\CardThumbsup;
use app\api\model\User;
use app\api\model\WorkUser;
use app\common\lib\Redis;
use app\common\lib\Socket;
use app\lib\enum\BehaviorStatusEnum;
use app\lib\enum\MessageStatusEnum;
use app\lib\exception\CardException;
use app\server\controller\Push;
use think\Db;


class Behavior
{
    /**
     * 获取行为并入库
     * @param $uid
     * @param $wu_id
     * @param $behavior
     * @param $details
     * @param $id
     * @return BehaviorModel
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function getBehavior($uid,$wu_id,$behavior,$details,$id){
        $data['url'] = request()->url();
        $data['user_id'] = $uid;
        $data['behavior_id'] = getRandChar(10);
        $data['wu_id'] = $wu_id;
        $userInfo = User::getUserInfoByUid($uid);
        $info = $this->getTypeData($behavior);
        $data['type'] = $info['type'];
        $data['content'] = $details;
        $data['weight'] = $info['weight'];
        $behaviorModel = new BehaviorModel();
        $result = $behaviorModel->createBehavior($data);
        //缓存行为结果
        $tag = Redis::getInstance()->get(20,"behavior:".$behavior.":id:".$id.":user:".$uid);
        if (empty($tag)){
            //异步计算成交率
            $array =[ 'function'=>'rate','args'=>['behavior'=>$behavior,'result'=>$result->toArray(),'wu_id'=>$wu_id]];
            $task = new Socket("tcp://127.0.0.1:27000",5);
            $task->asyncTask($array);
            //缓存行为
            Redis::getInstance()->set(20,"behavior:".$behavior.":id:".$id.":user:".$uid,$behavior,300);
        }
        //推送结果
        $news = $this->getMassgeInfo($userInfo,$result,$info['explain'],$details);
        $push = new Push($wu_id);
         $push->sendToClient($news);
        return $result;
    }
    /**
     * 用户点赞量
     * @param $uid
     * @param $w_id
     * @return mixed
     * @throws CardException
     * @throws \Exception
     */
    public function getThumbs($uid,$w_id){
        $thumbsInfo = explode('_',$w_id);
        $data['user'] = $uid;
        $data['w_id'] = $thumbsInfo[1];
        $info = CardThumbsup::findThumbs($uid,$thumbsInfo[1]);
       if (empty($info)){
           Db::startTrans();
           try {
               CardThumbsup::createThumbs($data);
               $num = (new CardBase())->thumgbsUp($thumbsInfo[1]);
               Db::commit();
           }catch (\Exception $e){
               Db::rollback();
               throw  $e;
           }
       }else{
          $cardBase =  (new CardBase())->getCardBase($thumbsInfo[1]);
          $num =  $cardBase->thumbsup_num;
       }
        return $num;
    }
    /**
     * 获取行为列表
     * @param $wu_id
     * @param $page
     * @param $size
     * @return array
     */
    public function getBehaviorList($wu_id,$page,$size){
        $info = [];
        $workUser = WorkUser::getBaseInfo($wu_id);
        //分表查询
        $behavior = new BehaviorModel();
        $result = $behavior->getBehaviorList($wu_id,$page,$size);
        if (!$result->isEmpty()){
            $arr =  $result->toArray();
            foreach ($arr as $key=>$value){
                if ($value['type'] == BehaviorStatusEnum::RANK){
                    $info[$key]['id'] = $workUser->id;
                    $info[$key]['url'] = $workUser->userimg->url;
                    $info[$key]['nickname'] = $workUser->name;
                }else{
                    $info[$key]['id'] = $value['user_info']['id'];
                    $info[$key]['url'] = $value['user_info']['avatar_url'];
                    $info[$key]['nickname'] = $value['user_info']['nickname'];
                }
                $info[$key]['times'] = $value['times'];
                $info[$key]['type'] = $value['type'];
                $info[$key]['content'] = $value['content'];
                $info[$key]['year'] = $value['minute'];
                $info[$key]['stamp'] = strtotime($value['minute']);
            };
        }
        return $info;
    }
    /**
     * 请求个人行为列表
     * @param $wu_id
     * @param $user_id
     * @param $timeInfo
     * @param $page
     * @param $size
     * @return string
     */
    public function getBehaviorListByUser($wu_id,$user_id,$page,$size){
        $info = [];
        //分表查询
        $behavior = new BehaviorModel();
        $result = $behavior->getBehaviorListByUser($wu_id,$user_id,$page,$size);
        if (!$result->isEmpty()) {
            $arr= $result->toArray();
            foreach ($arr as $key => $value) {
                $info[$key]['id'] = $value['user_info']['id'];
                $info[$key]['url'] = $value['user_info']['avatar_url'];
                $info[$key]['nickname'] = $value['user_info']['nickname'];
                $info[$key]['times'] = $value['times'];
                $info[$key]['type'] = $value['type'];
                $info[$key]['content'] = $value['content'];
                $info[$key]['year'] = $value['minute'];
                $info[$key]['stamp'] = strtotime($value['minute']);
            }
        }
        return $info;
    }

    /**
     * 根据分类查询行为
     * @param $type
     * @param $wu_id
     * @param $timeInfo
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBehaviorListByCategory($type,$wu_id,$timeInfo,$page,$size){
        $category = BehaviorType::where('pub_name','=',$type)->find();
      //分表查询
        $behavior = new BehaviorModel();
        $arr = $behavior->getBehaviorListByCategory($wu_id,$category->id,$timeInfo,$page,$size);
        $info=[];
        foreach ($arr as $key=>$value){
            $info[$key]['id'] = $value['user_info']['id'];
            $info[$key]['url'] = $value['user_info']['avatar_url'];
            $info[$key]['nickname'] = $value['user_info']['nickname'];
            $info[$key]['times'] = $value['count(id)'];
            $info[$key]['type'] = $category->name;
        }
        return $info;
    }

    /**
     * 获取个性为查询数量
     * @param $wu_id
     * @param string $type
     * @param $timeInfo
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCountInfo($wu_id,$type='all',$timeInfo){
        $data=[];
        if ($type == 'all'){
            $category = BehaviorType::getAllCategory();
            $list = $category->toArray();
            $ids = array_column($list,'id');
            $result  = $this->getCountNum($ids,$wu_id,$timeInfo);
            foreach ($result->toArray() as $value){
                $data[$value['type']['pub_name']] = $value['count(behavior_id)'];
            }
        }else{
            $category = BehaviorType::where('pub_name','=',$type)->find();
            $ids = [$category->id];
            $data[$type] = $this->getCountNum($ids,$wu_id,$timeInfo);
        }
        return $data;
    }
    /**
     * 获取客户信息
     * @param $wu_id
     * @return \think\model\relation\BelongsToMany
     */
    public function  getUser($wu_id,$time,$page,$size){
        $custom = [];
        //$info = UserWorkuser::getUserIdListByWuId($wu_id,$page,$size);
        $info = BehaviorModel::getBehaviorUser($wu_id,$page,$size);
        if (!$info->isEmpty()){
            $result = $info->toArray();
            $ids = array_column($result['data'],'user_id');
            $custom = User::getBehaviorListByIds($ids,$time);
            //排序
            $custom  = $custom->toArray();
            $last_names = array_column($custom,'behavior_count');
            array_multisort($last_names,SORT_DESC,$custom);;
        }
        return $custom;
    }
    /**
     * 根据客户id获取行为
     * @param $uid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserById($uid,$time){
        $array = [];
        $behavior = new BehaviorModel();
        $info =  $behavior->getBehaviorByUid($uid,$time);
        if (!$info->isEmpty()){
            $array  = $info->toArray();
            $num = array_column($array,'num');
            $sum = array_sum($num);
            foreach ($array as $key=>$value){
                $array[$key]['num'] =sprintf( "%.2f",$value['num']/$sum*100);
                $array[$key]['number'] =$value['num'];
            }
        }
        return $array;
    }
    /**
     * 获取统计数量
     * @param $type
     * @param $wu_id
     * @return int|string
     */
    private function getCountNum($type,$wu_id,$time){
        $behavior = new BehaviorModel();
        $num =$behavior->getBehaviorByType($type,$wu_id,$time);
        return $num;
    }
    /**
     * 行为获取
     * @param $uid
     * @param $behavior
     * @return mixed
     */
    private function getTypeData($behavior){
        $service = BehaviorType::getCategory($behavior);
        $data['weight'] = $service->weight;
        $data['type'] = $service->id;
        $data['content'] = $service->name;
        $data['explain'] = $service->explain;
        return $data;
    }

    /**
     * 获取行为统计数组
     * @return int|string
     */
    public function getBehaviorData($uid,$wu_id){
        $behavior = new BehaviorModel();
        $data =  $behavior->getBehaviorData($uid,$wu_id);
        return $data;
    }
    /**
     * 用户活跃度统计
     * @param $uid
     * @param $num
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getActiveData($uid,$wu_id,$num){
        if ($num == 15){
            $time = time()-15*3600*24;
        }
        $behavior = new BehaviorModel();
        $data = $behavior->getActiveData($uid,$wu_id,$time);
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $array['info'] = $data;
        $array['time'] = $times;
        return $array;
    }
    /**
     * 交互量统计
     * @param $uid
     * @return $this
     */
    public function getInteractionData($uid,$wu_id){
        $array=[];
        $behavior = new BehaviorModel();
        $result = $behavior->getInteractionData($uid,$wu_id);
        if (!$result->isEmpty()){
            $array  = $result->toArray();
            $num = array_column($array,'num');
            $sum = array_sum($num);
            foreach ($array as $key=>$value){
                $array[$key]['num'] =sprintf( "%.2f",$value['num']/$sum*100);
                $array[$key]['number'] =$value['num'];
            }
        }
        return $array;
    }
    /**
     * 获取全部行为量统计
     * @param $t_id
     * @return int|string
     */
    public function getAllBehaviorData($t_id){
        $behavior = new BehaviorModel();
        $data =  $behavior->getAllBehaviorData($t_id);
        return $data;
    }
    /**
     * 获取用户总活跃度统计
     * @param $uid
     * @param $num
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getAllActiveData($t_id,$num){
        if ($num == 15){
            $time = time()-15*3600*24;
        }
        $behavior = new BehaviorModel();
        $data = $behavior->getAllActiveData($t_id,$time);
        for ($i=0;$i<$num;$i++){
            $times[] = date('m-d',time()-($num-$i-1)*3600*24);
        }
        $array['info'] = $data;
        $array['time'] = $times;
        return $array;
    }
    /**
     * 要返回的数据结构
     * @param $data
     * @param $result
     * @return mixed
     */
    private function getMassgeInfo($data,$result,$content,$details){
        $info['id'] = $data->id;
        $info['url'] = $data->avatar_url;
        $info['nickname'] = $data->nickname;
        $info['times'] = $result->times;
        $info['type'] = 'behavior';
        $info['message_type'] = MessageStatusEnum::BEHAVIOR;//行为类型
        if (!empty($details)){
            $info['content'] = sprintf($content,$result->times,$details);
        }else{
            $info['content'] = sprintf($content,$result->times);
        }
        $info['year'] = date("Y-m-d H:i",$result->add_time);
        $info['stamp'] = strtotime($info['year']);
        return json_encode($info);
    }

    /**
     * 获取总交互量统计
     * @param $t_id
     * @return BehaviorModel
     * @throws \think\Exception
     */
    public function getAllInteractionData($t_id){
        $behavior = new BehaviorModel();
        $result = $behavior->getAllInteractionData($t_id);
        $num = array_column($result->toArray(),'num');
        $sum = array_sum($num);
        foreach ($result as $key=>$value){
            $value->num =sprintf( "%.2f",$value->num/$sum*100);
        }
        return $result;
    }
}